<template>
	<div class="px-5 py-4">
		<div class="pb-5 d-flex">
			<AlbumCover :src="albumInfo.picUrl || ''" size="210" bodyClass="rounded-5" class="me-5" />
			<div class="flex-grow-1 ms-2">
				<div class="d-flex align-items-center">
					<div class="MusicListTag rounded flex-center me-3">专辑</div>
					<div class="fs-3 fw-bold canSelect text-ellipsis" style="max-width: 400px">{{ albumInfo.name }}</div>
				</div>
				<div class="mt-4 d-flex">
					<PlayAllListBtn :musicList="songs" />
					<CustomButton v-if="collected" class="ms-2" icon="collected" @click="judgeIsCollected(0)">已收藏</CustomButton>
					<CustomButton v-else class="ms-2" icon="collect" @click="judgeIsCollected(1)">收藏</CustomButton>
					<!-- <CustomButton class="ms-2" icon="share">分享</CustomButton> -->
					<CustomButton @click="downloadAll" class="ms-2" icon="download">下载全部</CustomButton>
				</div>
				<div class="mt-4 mb-1">
					<span>标签：</span>
					<span class="colorA" v-for="(artist, artistIndex) in albumInfo?.artists || []" :key="artistIndex">
						<span
							@click="
								$route.query.artistId == artist.id ? $router.back() : $router.push({ name: 'artistDetail', query: { id: artist.id } })
							"
							class="cursor-pointer"
							>{{ artist.name }}</span
						>
						<span class="text-muted px-2" v-if="artistIndex != albumInfo?.artists?.length - 1">/</span>
					</span>
					<span v-if="!albumInfo?.artists?.length" class="text-black-50">无</span>
				</div>
				<div class="mt-2">
					<span>时间：</span>
					<span>{{ YYYYMMDD(albumInfo.publishTime) }}</span>
				</div>
			</div>
		</div>
		<HorizontalNav v-model:navs="navs" />
		<div class="boderLine w-100 border-top ms-2 mb-4"></div>
		<template v-if="currentActiveNavIndex === 0">
			<MusicList
				:startSpace="false"
				v-if="navs.find((item) => item.active)?.key === 0"
				:columns="columns"
				:dataSource="songs?.map((item, index) => ({ ...item, index: index }))"
			>
				<template #toolBar="{ id: musicId, index, name }">
					<span class="text-muted me-3">{{ String(index + 1).padStart(2, "0") }}</span>
					<span class="me-3">
						<LikedIcon
							class="cursor-pointer"
							v-if="!likedMusicList.includes(musicId)"
							@click="collectMusic(true, musicId)"
							width="15"
							height="15"
						/>
						<HaveLikedIcon class="cursor-pointer" v-else @click="collectMusic(false, musicId)" width="15" height="15" />
					</span>
					<DownloadMusicIcon @click="handleDownloadMusic({ id: musicId, name })" class="cursor-pointer" width="15" height="15" />
				</template>
			</MusicList>
		</template>
		<template v-if="currentActiveNavIndex === 2">
			<div class="fw-bold fs-5 mb-4">专辑介绍</div>
			<div class="text-muted mb-4">
				<p v-for="(txtItem, txtIndex) in albumInfo.description.split('\n')" :key="txtIndex">{{ txtItem }}</p>
			</div>
		</template>

		<CommonModal
			title="专辑收藏成功"
			:cancelable="true"
			@cancel="handleModalCancel"
			@confirm="handleModalConfirm"
			v-model:visible="commonModalVisible"
		>
			<div v-if="collectType" class="text-center text-muted">可以在“我的音乐-我的收藏”中查看</div>
			<div v-else class="text-center">确定不再收藏该专辑？</div>
		</CommonModal>
	</div>
</template>

<script lang="ts">
import { getAlbumApi, getSubedAlbumListApi, subAlbumApi } from "@/api/album";
import { likeMusic } from "@/api/discover";
import { getSongUrlApi } from "@/api/song";
import store from "@/store";
import { downloadMusic } from "@/utils/file";
import { addHaveUrl, playTime, YYYYMMDD } from "@/utils/filters";
import { AxiosResponseProps } from "@/utils/request";
import { computed, defineComponent, getCurrentInstance, reactive, toRefs } from "vue";
import { useRoute } from "vue-router";
import { AlbumDetail } from "./artistDetail.vue";
import { confirmedCollectKey } from "@/utils/_variable";
export default defineComponent({
	setup() {
		const route = useRoute();
		const state = reactive({
			songs: [],
			albumInfo: {},
			navs: [
				{
					title: "歌曲列表",
					key: 0,
					active: true,
				},
				{
					title: "评论（0）",
					key: 1,
				},
				{
					title: "专辑详情",
					key: 2,
				},
			],
			columns: [
				{
					title: "",
					span: 2,
					dataIndex: "toolBar",
					slots: { customRender: "toolBar" },
					colItemStyle: { "text-align": "center" },
				},
				{
					title: "音乐标题",
					span: 3,
					dataIndex: "name",
				},
				{
					title: "歌手",
					span: 3,
					dataIndex: "ar",
					render: (text) => {
						return text.map((item) => item.name).join("、");
					},
				},
				{
					title: "专辑",
					span: 3,
					dataIndex: "al",
					render: (text) => {
						return text.name;
					},
				},
				{
					title: "时长",
					span: 1,
					dataIndex: "dt",
					render: (text) => {
						return playTime(text);
					},
				},
			],
			likedMusicList: computed(() => store.state.likedMusicList),
			subAlbumList: [],
			commonModalVisible: false,
			collectType: 0,
		});
		const currentActiveNavIndex = computed(() => state.navs.map((item, index) => ({ ...item, index })).find((item) => item.active)?.index || 0);
		const {
			appContext: {
				config: {
					globalProperties: { $toast },
				},
			},
		} = getCurrentInstance();
		const { id } = route.query;
		const collected = computed(() => state.subAlbumList.some((item) => item.id == id));
		const getArtistAlbum = () => {
			getAlbumApi(id as string).then(async (res: Partial<AlbumDetail>) => {
				if (res.code === 200) {
					state.navs[1].title = `评论（${res.album?.info?.commentCount || 0}）`;
					state.albumInfo = res.album;
					state.songs = await addHaveUrl(res.songs);
				}
			});
		};
		getArtistAlbum();
		const handleDownloadMusic = ({ id, name }) => {
			getSongUrlApi({ id }).then((res: AxiosResponseProps) => {
				if (res.code === 200) {
					let urls = res.data;
					if (urls && urls.length) {
						downloadMusic(urls[0].url, name)
							.then(() => {
								$toast.success("已添加至下载");
							})
							.catch(() => {
								$toast.warn("下载失败");
							});
					} else {
						$toast.warn("获取音乐链接失败");
					}
				}
			});
		};
		const collectMusic = (like, id) => {
			likeMusic({ id, like }).then(async (res: any) => {
				if (res.code === 200) {
					await store.dispatch("getLikedMusicList");
					$toast.success(like ? "已添加到我喜欢的音乐" : "取消喜欢成功");
				}
			});
		};
		const downloadAll = () => {
			if (!state.songs.length) return $toast.warn("歌单暂无歌曲，请添加一些再来下载吧~");
			state.songs.forEach((item, index) => {
				setTimeout(() => {
					handleDownloadMusic({ id: item.id, name: item.name });
				}, 60 * index);
			});
		};
		const getSubedAlbumList = () => {
			return getSubedAlbumListApi().then((res: AxiosResponseProps) => {
				if (res.code === 200) {
					state.subAlbumList = res.data;
				}
			});
		};
		getSubedAlbumList();
		const subAlbum = (isCollected) => {
			subAlbumApi({ id: id as string, t: isCollected }).then(async (res: AxiosResponseProps) => {
				if (res.code === 200) {
					await getSubedAlbumList();
					if (isCollected) {
						let confirmed = false;
						try {
							confirmed = sessionStorage[confirmedCollectKey] && JSON.parse(sessionStorage[confirmedCollectKey]) === true;
						} catch {
							confirmed = false;
						}
						if (confirmed) {
							$toast.success("已收藏");
						} else {
							state.commonModalVisible = true;
						}
					} else {
						$toast.success("已取消收藏");
						state.commonModalVisible = false;
					}
				}
			});
		};
		const judgeIsCollected = (isCollected) => {
			state.collectType = isCollected;
			if (isCollected) {
				subAlbum(1);
			} else {
				state.commonModalVisible = true;
			}
		};
		const handleModalCancel = () => {
			state.commonModalVisible = false;
		};
		const handleModalConfirm = () => {
			if (state.collectType) {
				state.commonModalVisible = false;
				sessionStorage[confirmedCollectKey] = true;
			} else {
				subAlbum(0);
			}
		};
		return {
			...toRefs(state),
			YYYYMMDD,
			handleDownloadMusic,
			collectMusic,
			downloadAll,
			subAlbum,
			collected,
			handleModalCancel,
			handleModalConfirm,
			judgeIsCollected,
			currentActiveNavIndex,
		};
	},
});
</script>

<style scoped lang="scss">
.MusicListTag {
	height: 18px;
	width: 32px;
}
.boderLine {
	margin-top: -7px;
	position: relative;
	z-index: -1;
}
.primaryTheme {
	.MusicListTag {
		border: 1px solid $primary;
		color: $primary;
	}
}
.darkTheme {
	.MusicListTag {
		border: 1px solid $dark;
		color: $dark;
	}
}
.freeTheme {
	.MusicListTag {
		border: 1px solid $free;
		color: $free;
	}
}
</style>
